<template>
  <div class="app-container">
    <!-- <div>
      <el-link href="" type="primary">平台使用方法.doc</el-link><br>
      <el-link href="" type="primary">体质测试标准.xls</el-link><br>
      <el-link href="" type="primary">体测数据格式标准.xls</el-link><br>
    </div> -->
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="课程名称"
        width="120"
      />
      <el-table-column
        prop="time"
        label="上课时间"
        width="150"
      />
      <el-table-column
        prop="teacher"
        label="教师"
        width="150"
      />
      <el-table-column
        prop="total"
        label="班级人数"
        width="150"
      />
      <el-table-column
        prop="totalCompleted"
        label="已完成提交数量"
        width="150"
      />
      <el-table-column
        label="操作"
        width="250"
      >
        <template slot-scope="{row, $index}">
          <el-link type="primary" @click="download(row)">模板下载</el-link>
          <el-upload
            :ref="'class'+$index"
            class="upload"
            :action="action"
            name="upload_file"
            accept=".xlsx"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="true"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :data="{task_id}"
            :show-file-list="false"
            :limit="1"
          >
            <el-link type="primary" @click="submitUpload('class'+$index)">上传</el-link>
          </el-upload>
          <router-link :to="{path:'./edit',query: { row,task_id }}">
            <el-link type="primary">编辑</el-link>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import * as teacher from '@/api/teacher.js'
import { mapGetters } from 'vuex'
const Host = process.env.VUE_APP_BASE_URL
export default {
  data() {
    return {
      action: Host + '/StuBasicInfoBLL/uploadSroceFile',
      fileList: [],
      listLoading: true,
      tableData: null,
      task_id: null
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const task = JSON.parse(localStorage.task)
    if (task) {
      this.task_id = task.id
      if (this.task_id) this.fetchData(this.task_id)
      else this.$router.push('/teacher/task')
    } else this.$router.push('/teacher/task')
  },
  methods: {
    fetchData(task_id) {
      this.listLoading = true
      const t_id = this.name
      teacher.classList({ task_id, t_id }).then(response => {
        this.tableData = response.data
        console.log(this.tableData)
        this.listLoading = false
      })
    },
    upload(row) {
      console.log(row)
    },
    download(row) {
      // const userd = user
      // console.log(userd)
      const filename = row.name + row.time + '.xlsx'
      const id = row.id
      teacher.download(id).then(response => {
        const headerDisplay = {
          id: '学号', name: '姓名', sex: '性别', 'height': '身高', 'weight': '体重',
          'pulmonary': '肺活量', 'run50': '50米跑', 'jump': '立定跳远', 'flexion': '坐位体前屈',
          'run800': '800米跑', 'run1000': '1000米跑', 'abdominal_curl': '一分钟仰卧起坐',
          'pull_up': '引体向上', 'left_eye': '左眼视力', 'right_eye': '右眼视力'
        }
        const newData = [headerDisplay, ...response.data]
        const workSheet =
        XLSX.utils.json_to_sheet(newData, {
          header: [
            'id', 'name', 'sex', 'height', 'weight', 'pulmonary', 'run50', 'jump',
            'flexion', 'run800', 'run1000', 'abdominal_curl', 'pull_up', 'left_eye', 'right_eye'
          ],
          skipHeader: true
        })
        const blob = this.sheet2blob(workSheet, filename)
        const url = URL.createObjectURL(blob)
        const eleLink = document.createElement('a')
        eleLink.style.display = 'none'
        eleLink.target = '_blank'
        eleLink.href = url
        eleLink.download = filename
        document.body.appendChild(eleLink)
        eleLink.click()
        document.body.removeChild(eleLink)
      })
    },
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1'
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {}
      }
      workbook.Sheets[sheetName] = sheet
      // 生成excel的配置项
      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary'
      }
      var wbout = XLSX.write(workbook, wopts)
      var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
      // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      }
      return blob
    },
    submitUpload(name) {
      this.$refs[name].submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    uploadSuccess(response, file, fileList) {
      console.log(response, file, fileList)
    },
    uploadError(err, file, fileList) {
      console.err(err, file, fileList)
    }
  }
}
</script>
<style scoped>
/* .el-upload{
  display: block;
  width: 20px;
} */
.upload{
  display: inline-block;
  padding: 12px 23px;
}
</style>
